#!/bin/sh
##BEGIN_INTRODUCTION##	This script is used to control the whole service.
##END_INTRODUCTION##

#####################  Build in Things   ######################
#. $Function_Top/Include/Enviroment_Config.inc
Call_Path=$(pwd) #Where this call from?
#Where is here?
if [ -n "$Function_Path" ];then
	Here_Path=$Function_Path
else
	Here_Path=$(dirname $(readlink -f $0))
fi
#Who am I?
if [ -n "$Function_Name" ];then
	File_Name=$Function_Name.func
else
	File_Name=${0##*/};
	Function_Name=${File_Name%.*};
fi

echo_introduction() #Introduce myself
{
	if [ -n "$1" ];then
	FILE_Content=$(cat < $1)
	else
	FILE_Content=$(cat < $Here_Path/$File_Name)
	fi
	INTRO=${FILE_Content#*##BEGIN_INTRODUCTION##};
	INTRO=${INTRO%%##END_INTRODUCTION##*};
	echo "$INTRO"
}

echo_help() #Echo my help or others'
{
	if [ -n "$1" ];then
		FILE_Content=$(cat < $1)
	else
		FILE_Content=$(cat < $Here_Path/$File_Name)
	fi
	HELP=${FILE_Content##*##BEGIN_HELP##};
	HELP=${HELP%##END_HELP##*};
	echo "usage:  $Function_Name [options values]"
	echo options:"$HELP"
}

##################### other functions below ######################

install()
{
  if [ "`uname -s`" != "Darwin" ]; then
      # Install UDEV rules for USB device
      echo "Installing USB rules ..."
      sudo cp ${Here_Path}/orbbec-usb.rules /etc/udev/rules.d/558-orbbec-usb.rules
      echo "Installed USB rules."
  fi
  
  sudo apt-get update
  sudo apt-get install -y python3 python3-pip python3-dev meshlab
  sudo pip3 install -i https://pypi.douban.com/simple --upgrade pip
  sudo pip3 install -i https://pypi.douban.com/simple -r $Here_Path/requirements.txt
}

start_service()
{
  echo "Installing service, please do not remove this folder for service running ..."
  cp $Here_Path/osdk.service /tmp/osdk.service
  echo "User=$USER" >> /tmp/osdk.service
  echo "ExecStart=/usr/bin/python3 $Here_Path/osdk.py" >> /tmp/osdk.service
  echo "Environment=XAUTHORITY=/home/$USER/.Xauthority" >> /tmp/osdk.service
  echo "WorkingDirectory=$Here_Path" >> /tmp/osdk.service

  sudo cp /tmp/osdk.service /etc/systemd/system

  sudo systemctl enable osdk.service
  sudo systemctl restart  osdk.service

  echo "Smart body service installed, please use 'systemctl stop osdk' to stop the service."
}

start() # Start the service
{
  python3 $Here_Path/osdk.py
}

######################  main below  ##############################
if [ -n "$1" ];then
	while [ -n "$1" ]; do
	case $1 in
##BEGIN_HELP##
		-h)     shift 1;echo_help;exit 1;;                   #Show usages 
		-i)     shift 1;echo_introduction;exit 1;;           #Show introduction 
		-edit)  shift 1;gedit $Here_Path/$File_Name;exit 1;; #Edit this function 
		-*)     echo "error: no such option $1. -h for help";exit 1;; 
		*)      $*;exit 1;;                                  #Call function here
##END_HELP##
	esac
	done
else
	start
fi
#echo ---------------------End Of $Function_Name-----------------------


